#SingleInstance, Force
SendMode Input
SetWorkingDir, %A_ScriptDir%
; re tool


R(str, match, replace:="") {  ; replace all match in str
    Return RegExReplace(str, match, replace)
}



R_AR(ar) {  ; replace multi for array
    ar[1] := R(ar[1], ar[2], ar[3])

    If(ar.Length() > 3) {
        index := 3
        While(index <= ar.Length()) {
            ar[1] := R(ar[1], ar[++index], ar[++index])
        }
    }

    Return ar[1]
}



R_ULT(row, mode:="0") {
    pattern :="U"  ; Upper
    If (mode == "00") {
        pattern :="L"  ; Lower
    }
    Else If (mode == "1") {
        pattern :="T"  ; Title
    }

    Return R(row, "\b([a-zA-Z][a-zA-Z0-9_]*)\b", "$" pattern "1")
}



R_MD(v:= "", mode:="0") {
    ; format for MD

    v := S_EmptyClip(v)

    v := R(v, "([。；][\s\r\n]*)", "`n")

    v := R_ZH_Punctuation(R_ZH_EN_Space(v))

    ; del extra line
    v := R(v, "[`r`n]{3,}", "`n`n")

    ; tab 2 space*4
    v := R(v, "`t", "    ")

    ; del space in tail
    v := R(v, "\s+?$", "")

    ; del line in head, tail
    v := R(v, "`n+?$", "")
    v := R(v, "^`n+?", "")

    ; del all line
    If(mode != "0") {
        v := R(v, "[`r`n]+", "`n")
    }
    Return v
}



R_ZH_Punctuation(v) {
    ; Replace whitespace (Spaces, tabs, etc.) and invisible Spaces

    ; 0 1 2　3    4 5​6 7
    v := R(v, "[​   　 ]", " ")

    ; Chinese punctuation
    ; ，。、！？；《》（）“”‘’——

    v :=S_Replace(v, "，", ", ")
    v :=S_Replace(v, "、", ", ")
    v :=S_Replace(v, "；", "; ")
    v := S_Replace(v, "：", ": ")
    v := S_Replace(v, "？", "? ")
    v := S_Replace(v, "！", "! ")

    v := S_Replace(v, "“", " """)
    v := S_Replace(v, "”", """ ")
    v := S_Replace(v, "‘", " '")
    v := S_Replace(v, "’", "' ")

    v := S_Replace(v, "…", "...")
    v := S_Replace(v, "—", "-")
    v := S_Replace(v, "–", "-")
    ; v := S_Replace(v, "《", " <")
    ; v := S_Replace(v, "》", "> ")

    v := S_Replace(v, "（", "(")
    v := S_Replace(v, "）", ")")
    v := S_Replace(v, "【", " [")
    v := S_Replace(v, "】", "] ")

    v := S_Replace(v, "·", "`n")
    v := S_Replace(v, "。", "`n")
    v := R(v, "[」「]", " ")
    v := R(v, "[.。]+?[\n\r]", "")

    ; v := R(v , "([一-龥])([a-zA-Z0-9])", "$1 $2")

    Return v
}



R_ZH_EN_Space(v) {
    ; Add Spaces for Chinese and English characters

    ; v := R(v , "([一-龥])([a-zA-Z0-9])", "$1 $2")
    ; v := R(v , "([a-zA-Z0-9])([一-龥])", "$1 $2")

    v := R(v, "([\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}])([a-zA-Z0-9])", "$1 $2")
    v := R(v, "([a-zA-Z0-9])([\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}])", "$1 $2")

    ; Remove extra Spaces around symbols
    ; v := R(v, "\s+?([,.?!-])", " $1")
    ; v := R(v, "([,.?!-])\s+?", "$1 ")

    Return v
}
